package com.example.administrator.alarmmanagerdemo1;

import android.content.Intent;
import android.icu.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.AlarmManager;
import android.app.PendingIntent;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static MainActivity appRef = null;
    private Button bcall,bexit;
    boolean k = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        appRef = this;
        bcall = (Button) findViewById(R.id.button01);
        bcall.setOnClickListener(this);
        bexit = (Button) findViewById(R.id.button02);
        bexit.setOnClickListener(this);

    }

    public static MainActivity getApp(){
        return appRef;
    }

    public void btEvent(String data){
        setTitle(data);
    }

    public void onClick(View arg0){
        if (arg0 == bcall){
            setTitle("Waiting for 5");
            Intent intent = new Intent(MainActivity.this,AlarmReceive.class);
            PendingIntent p_intent = PendingIntent.getBroadcast(MainActivity.this,0,intent , 0);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND,3);
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),p_intent);
        }

        if (arg0 == bexit){
            Intent intent = new Intent(MainActivity.this,AlarmReceive.class);
            PendingIntent p_intent = PendingIntent.getBroadcast(MainActivity.this,0,intent , 0);
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.cancel(p_intent);
            finish();
        }
    }

}
